package com.example.springcloudwinter.service;

import com.example.springcloudwinter.bo.BusinessBo;
import com.example.springcloudwinter.bo.CartBo;
import com.example.springcloudwinter.bo.FoodBo;
import com.example.springcloudwinter.bo.OrderBo;
import com.example.springcloudwinter.feign.CartFeignClient;
import com.example.springcloudwinter.mapper.OrderMapper;
import com.example.springcloudwinter.dto.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartFeignClient cartFeignClient;

    private static final int MAX_POINT = 500;
    public ResultEntity<?> getHistoryOrderList(String userId){
        ResultEntity<List<Map<String,Object>>> result=new ResultEntity<>();
        List<Map<String,Object>> maplist=new ArrayList<>();//存放最终返回的数据集，每个订单所对应的完整的食物，商家和订单信息
        List<OrderBo> orderList=new ArrayList<>();//存放得到的订单集，用于获取订单号和保存订单信息
        List<FoodBo> foodlist;//存放订单的完整食物信息
        int orderId;
        try {
            orderList=orderMapper.getOrdersByUserId(userId);
            orderList.sort(new Comparator<OrderBo>() {
                @Override
                public int compare(OrderBo o1, OrderBo o2) {
                    return -o1.getOrderDate().compareTo(o2.getOrderDate());
                }
            });
            for (OrderBo orderBo : orderList) {
                BusinessBo restaurant;//存放商家信息
                orderId = orderBo.getOrderId();
                foodlist = orderMapper.getFoodById8Lightweight(orderId, userId);
                restaurant = orderMapper.getByRestaurantId8Lightweight(orderId, userId);
                Map<String, Object> map = new HashMap<>();
                map.put("foods", foodlist);
                map.put("order", orderBo);
                map.put("restaurant", restaurant);
                maplist.add(map);
            }
            result.setDetail(maplist).setCode(200);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultEntity<?> getOrderById(int orderId,String userId){
        ResultEntity<Map<String,?>> result=new ResultEntity<>();
        List<FoodBo> foodlist;
        OrderBo order;
        BusinessBo restaurant;
        List<OrderBo> validPoints;
        try {
            validPoints = orderMapper.getValidPoints(userId);
            order=orderMapper.getOrderById(orderId, userId);
            if(order==null){
                result.setCode(601);
                return result;
            }
            foodlist=orderMapper.getFoodById(orderId, userId);
            restaurant= orderMapper.getByRestaurantId(orderId, userId);
            int points = 0;
            // 限定积分使用最大值不能超出订单上限
            double max = MAX_POINT > order.getOrderTotal()*100 ? MAX_POINT : order.getOrderTotal()*100;
            for (OrderBo orderEntity : validPoints) {
                points += orderEntity.getRemainingPoints();
                if (points >= MAX_POINT) {
                    orderEntity.setRemainingPoints(points - MAX_POINT);
                    points = MAX_POINT;
                    break;
                }
            }
            Map<String,Object> map=new HashMap<>();
            map.put("foods",foodlist);
            map.put("order",order);
            map.put("restaurant",restaurant);
            map.put("points", points);
            result.setDetail(map).setCode(200);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultEntity<?> createOrder(String userId,int businessId,double orderTotal,int daId){
        ResultEntity<Integer> result=new ResultEntity<>();
        try {
            OrderBo order = new OrderBo();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            order.setOrderDate(sdf.format(new Date()));
            order.setOrderState(0);
            order.setOrderTotal(orderTotal);
            order.setBusinessId(businessId);
            order.setUserId(userId);
            order.setDaId(daId);
            orderMapper.createOrder(order);
            int orderId=order.getOrderId();
            List<CartBo> cart=orderMapper.listCart(businessId,userId);
            orderMapper.removeCart(userId,businessId);
            for (CartBo cartBo : cart) {
                orderMapper.insertOrderDetailet(orderId, cartBo.getFoodId(), cartBo.getQuantity());
            }
            result.setCode(200).setDetail(orderId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultEntity<?> updatePoint(int orderId,int remainPoint){
        try {
            orderMapper.updatePoints(orderId,remainPoint);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ResultEntity<>();
    }
}
